package com.triones.yjj.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.SysUserPost;
import com.triones.yjj.entity.*;
import com.triones.yjj.entity.vo.MemberDetailVO;
import com.triones.yjj.entity.vo.MemberVO;
import com.triones.yjj.entity.vo.WxInviteRewardConfigVO;
import com.triones.yjj.mapper.*;
import com.triones.yjj.service.MemberActivityRelateService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

/**
 * 客户活动关联 service 业务实现
 *
 * @Author: triones
 */
@Service
@RequiredArgsConstructor
public class MemberActivityRelateServiceImpl implements MemberActivityRelateService {

    private final MemberActivityRelateMapper memberActivityRelateMapper;

    private final ActivityMapper activityMapper;

    private final MemberMapper memberMapper;

    private final OrderMapper orderMapper;

    private final ShareRecordMapper shareRecordMapper;

    @Override
    public Boolean createMemberActivityRelate(Long memberId, Long activityId) {
        MemberDO memberDO = memberMapper.selectById(memberId);
        if (memberDO == null) {
            throw new SecurityException("没有该客户信息");
        }
        ActivityDO activityDO = activityMapper.selectById(activityId);
        if (activityDO != null) {
            MemberActivityRelateDO activityRelateDO = this.selectOne(memberId, activityId);
            if (activityRelateDO == null) {
                activityRelateDO = new MemberActivityRelateDO();
                activityRelateDO.setActivityId(activityDO.getId());
                activityRelateDO.setMemberId(memberId);
                activityRelateDO.setMemberWxId(memberDO.getWxUserId());
                activityRelateDO.setUserId(activityDO.getUserId());
                memberActivityRelateMapper.insert(activityRelateDO);
            }
        }
        return true;
    }

    @Override
    public Boolean updateMemberActivityOrderId(Long memberId, Long activityId, Long orderId) {
        LambdaQueryWrapper<OrderDO> orderWrapper = Wrappers.lambdaQuery(OrderDO.class);
        orderWrapper.eq(OrderDO::getId,orderId)
            .eq(OrderDO::getMemberId,memberId)
            .eq(OrderDO::getActivityId,activityId);
        OrderDO orderDO = orderMapper.selectOne(orderWrapper);
        if (orderDO == null) {
            throw new SecurityException("订单不存在");
        }
        MemberActivityRelateDO activityRelateDO = this.selectOne(memberId, activityId);
        if (activityRelateDO != null) {
            activityRelateDO.setLastOrderId(orderDO.getId());
            memberActivityRelateMapper.updateById(activityRelateDO);
        }
        return true;
    }

    @Override
    public MemberActivityRelateDO selectOne(Long memberId, Long activityId) {
        LambdaQueryWrapper<MemberActivityRelateDO> wrapper = Wrappers.lambdaQuery(MemberActivityRelateDO.class);
        wrapper.eq(MemberActivityRelateDO::getActivityId,activityId)
            .eq(MemberActivityRelateDO::getMemberId,memberId);
        return memberActivityRelateMapper.selectOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMemberActivityInviteTotal(String scene, Long memberId, Long activityId, Long shareId) {
        MemberVO shareMemberVO = memberMapper.selectDetailByShareId(shareId);
        if (shareMemberVO != null) {
            MemberVO memberVO = memberMapper.selectVoById(memberId);
            if(ObjectUtil.isNotEmpty(memberVO)){
                if (shareMemberVO.getId().equals(memberVO.getId())) {
                    return true;
                }
            }
            /**
             * 查询活动邀请规则
             */
            ActivityDO activityDO = activityMapper.selectById(activityId);
            if (activityDO == null) {
                throw new SecurityException("活动不存在");
            }
            HashMap map = JSONUtil.toBean(activityDO.getContent(), HashMap.class);
            if(ObjectUtil.isEmpty(map)){
                throw new SecurityException("活动内容为空");
            }
            WxInviteRewardConfigVO wxDistributionVO = JSONUtil.toBean(map.get("invite_reward_config").toString(), WxInviteRewardConfigVO.class);
            if (wxDistributionVO.getIsOpenInvite()) {
                if ("orderPay".equals(scene)) {
                    if ("ruleA".equals(wxDistributionVO.getComputeWay())) {
                        Long orderCount = orderMapper.selectCount(new LambdaQueryWrapper<OrderDO>().eq(OrderDO::getMemberId, memberId)
                            .eq(OrderDO::getActivityId, activityId).ne(OrderDO::getShareId,shareId));
                        if (orderCount > 0) {
                            return false;
                        }
                        MemberActivityRelateDO memberActivityRelateDO = this.selectOne(shareMemberVO.getId(), activityId);
                        if (memberActivityRelateDO != null) {
                            memberActivityRelateDO.setInviteTotal(memberActivityRelateDO.getInviteTotal() + 1);
                            memberActivityRelateMapper.updateById(memberActivityRelateDO);
                        }
                    }
                } else if ("browse".equals(scene)) {
                    if ("ruleB".equals(wxDistributionVO.getComputeWay())) {
                        Long recordNumber = shareRecordMapper.selectCount(new LambdaQueryWrapper<ShareRecordDO>()
                            .ne(ShareRecordDO::getShareId, shareId).eq(ShareRecordDO::getPassiveMemberId, memberId));
                        if (recordNumber > 0) {
                            return false;
                        }
                        MemberActivityRelateDO memberActivityRelateDO = this.selectOne(shareMemberVO.getId(), activityId);
                        if (memberActivityRelateDO != null) {
                            memberActivityRelateDO.setInviteTotal(memberActivityRelateDO.getInviteTotal() + 1);
                            memberActivityRelateMapper.updateById(memberActivityRelateDO);
                        }
                    }
                }
            }
        }
        return true;
    }
}
